package com.bstek.poc.service;

import java.util.Timer;
import java.util.TimerTask;
import jni.cylan.com.Constants;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class HeartbeatService extends Service {
    public static String TAG = "HeartbeatService";
    public final static String HEART_BEAT_BROAD="heart_beat_broad";
    public Handler handler;
    MyTimerTask ttask = null;
    public int nLostTime = 0;
    public Timer timer = null;

    public static final String SESSION_EXCPETION = "com.example.hello.SessionExpception";
    public static final String ERROR_NETWORK_HEARTBEAT = "心跳检测VPN异常";

    final static int HBMSG_SHORTTIMER = 1;
    final static int HBMSG_LONGTIMER = 2;
    final static int HBMSG_SIGNAL_BAD = 3;
    final static int HBMSG_LOSTTIME = 5;
    int count = 0;
    boolean isfinish = false;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        startHeartbeat();
        return START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {
        try {
            stop();
        } catch(Exception e) {
            e.printStackTrace();
        }

        handler = null;
        ttask = null;
        nLostTime = 0;
        timer = null;
        count = 0;
        isfinish = false;

        super.onDestroy();
    }

    private void startHeartbeat() {
        try {
            System.setProperty("keepAlive", "false");
            timer = new Timer();
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case HBMSG_SHORTTIMER:
                            ttask = new MyTimerTask();
                            timer.schedule(ttask, 5 * 1000);
                            break;
                        case HBMSG_LONGTIMER:
                            ttask = new MyTimerTask();
                            timer.schedule(ttask, 60 * 1000);
                            break;
                        case HBMSG_SIGNAL_BAD:
                            Toast.makeText(HeartbeatService.this,ERROR_NETWORK_HEARTBEAT,
                                    Toast.LENGTH_SHORT).show();
                            ttask = new MyTimerTask();
                            timer.schedule(ttask, 5 * 1000);
                            break;
                        case 0:
                            if (msg.obj != null) {

                            }

                            sendBroadcast(new Intent(SESSION_EXCPETION).putExtra(
                                    "error", msg.arg1));

                        default:
                            break;

                    }
                }
            };

            handler.sendEmptyMessage(HBMSG_SHORTTIMER);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            try {

                if (isfinish)
                    return;

                int nRet = -1;

                try {
                    nRet = jni.cylan.com.cylanlib.CSessionSendHeartbeat();

                    if(nRet==0)
                        heartBeatSuccess();

                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (!isfinish) {
                    if (nRet == 0) {
                        handler.sendEmptyMessage(HBMSG_LONGTIMER);
                        nLostTime = 0;
                    } else {
                        Log.i(TAG, "CSessionSendHeartbeat failed! nLostTime = " + nLostTime);
                        if (nRet == Constants.ERR_SGACALL) {
                            handler.removeCallbacksAndMessages(null);
                            isfinish = true;
                            handler.sendMessage(handler.obtainMessage(0, null));
                            return;
                        }

                        if (++nLostTime < HeartbeatService.HBMSG_LOSTTIME)
                        {
                            if (nLostTime == 3) {//网咯信号不好,第三次还没反应.
                                handler.sendEmptyMessage(HBMSG_SIGNAL_BAD);
                            }else {
                                handler.sendEmptyMessage(HBMSG_SHORTTIMER);
                            }

                        }

                    }
                }
                if (nLostTime >= HeartbeatService.HBMSG_LOSTTIME) {
                    String sError = null;

                    sError = jni.cylan.com.cylanlib
                            .GetErrorInfo(HeartbeatService.this
                                    .getApplicationContext(), nRet);

                    handler.removeCallbacksAndMessages(null);
                    isfinish = true;
                    handler.sendMessage(handler.obtainMessage(0, sError));

                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    public void stop() {
        ttask.cancel();
        timer.cancel();
        isfinish = true;
        handler.removeCallbacks(ttask);
        handler.removeCallbacksAndMessages(null);
    }

    private void heartBeatSuccess(){
        Intent intent=new Intent(HEART_BEAT_BROAD);
        sendBroadcast(intent);
    }
}
